﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RenderShadowMap : MonoBehaviour
{
    public Transform DirectionalLight;
    public RenderTexture RenderTexture;
    public Camera depthCamera;

    Matrix4x4 sm = new Matrix4x4();

    private Matrix4x4 lightVP;

    private void Start()
    {
        sm.m00 = 0.5f;
        sm.m11 = 0.5f;
        sm.m22 = 0.5f;
        sm.m03 = 0.5f;
        sm.m13 = 0.5f;
        sm.m23 = 0.5f;
        sm.m33 = 1;

        depthCamera.backgroundColor = new Color(1, 1, 1, 0);
        depthCamera.targetTexture = RenderTexture;
        depthCamera.SetReplacementShader(Shader.Find("Unlit/DepthTextureShader"), "RenderType");
    }

    private void Update()
    {
        Debug.Log("World to camera " + depthCamera.worldToCameraMatrix);

        Debug.Log("World to light " + DirectionalLight.worldToLocalMatrix);

        depthCamera.Render();
        Matrix4x4 tm = GL.GetGPUProjectionMatrix(depthCamera.projectionMatrix, false) * depthCamera.worldToCameraMatrix;
        tm = sm * tm;

        Matrix4x4 lightVP = depthCamera.projectionMatrix * DirectionalLight.worldToLocalMatrix;

        Shader.SetGlobalMatrix("lightVP", tm);
        Shader.SetGlobalMatrix("projectionMatrix", tm);
        Shader.SetGlobalTexture("shadowMap", RenderTexture);
    }
}
